package com.newa.dao;

import java.util.ArrayList;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.newa.beans.Work;


public class DAOWorks {
	private Session session;

	public DAOWorks(Session session) {
		super();
		this.session = session;
	}
	
	public Work getWorkById(int id){
		Transaction tx = session.beginTransaction();
		try {
			Work wrk = (Work) session.get(Work.class, id);
			return wrk;
		} catch (Exception e) {
			tx.rollback();
			tx = null;
			throw new RuntimeException(e);
		} finally {
			if (tx != null) {
				tx.commit();
			}
		}
		
	}
	
	public ArrayList<Work> getAllWorks(){
		Transaction tx = session.beginTransaction();
		try {
			Query qu = session.createQuery("from Work order by ID");
			ArrayList<Work> res = new ArrayList<Work>(qu.list());
			return res;
		} catch (Exception e) {
			tx.rollback();
			tx = null;
			throw new RuntimeException(e);
		} finally {
			if (tx != null) {
				tx.commit();
			}
		}
	}
	
	public ArrayList<Work> getAllWorksBySectionId(int id){
		Transaction tx = session.beginTransaction();
		try {
			Query qu = session.createQuery("from Work wrk where wrk.SECTION_ID = "+id);
			ArrayList<Work> res = new ArrayList<Work>(qu.list());
			return res;
		} catch (Exception e) {
			tx.rollback();
			tx = null;
			throw new RuntimeException(e);
		} finally {
			if (tx != null) {
				tx.commit();
			}
		}
	}
	
	public boolean createWork(Work wrk) {
		Transaction tx = session.beginTransaction();
		try {
			Object ret = session.save(wrk);
			boolean res = ret != null ? true : false;
			return res;
		} catch (Exception e) {
			tx.rollback();
			tx = null;
			throw new RuntimeException(e);
		} finally {
			if (tx != null) {
				tx.commit();
			}
		}

	}


	public void updateWork(Work wrk) {
		Transaction tx = session.beginTransaction();
		try {
			session.update(wrk);
		} catch (Exception e) {
			tx.rollback();
			tx = null;
			throw new RuntimeException(e);
		} finally {
			if (tx != null) {
				tx.commit();
			}
		}

	}

	public void deleteWorkById(int id) {
		Transaction tx = session.beginTransaction();
		try {
			Work sec = (Work) session.get(Work.class, id);
			session.delete(sec);
		} catch (Exception e) {
			tx.rollback();
			tx = null;
			throw new RuntimeException(e);
		} finally {
			if (tx != null) {
				tx.commit();
			}
		}

	}
	
	
	public Session closeSession() {
		try {
			if (session != null) {
				session.flush();
				session.clear();
			}
			return session;
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			session = null;
		}
	}
}
